<template>
  <div class="profile-container">
    <div class="profile-card">
      <div class="card-header">
        <el-icon class="header-icon"><UserFilled /></el-icon>
        <h2 class="profile-title">个人信息</h2>
        <p class="profile-subtitle">管理您的个人资料信息</p>
      </div>

      <el-tabs v-model="activeTab" class="profile-tabs">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form
              :model="data.user"
              label-width="120px"
              ref="formRef"
              :rules="rules"
              class="form-section"
          >
            <el-form-item label="账号">
              <el-input disabled v-model="data.user.username" />
            </el-form-item>
            <el-form-item label="真实姓名">
              <el-input disabled v-model="data.user.realName" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="data.user.phone" placeholder="请输入手机号码" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="data.user.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 学生信息 -->
        <el-tab-pane v-if="isStudent" label="学生信息" name="student">
          <el-form class="form-section">
            <el-form-item label="学号">
              <el-input disabled v-model="data.user.studentInfo.studentNumber" />
            </el-form-item>
            <el-form-item label="院系">
              <el-input disabled v-model="data.user.studentInfo.department" />
            </el-form-item>
            <el-form-item label="专业">
              <el-input disabled v-model="data.user.studentInfo.major" />
            </el-form-item>
            <el-form-item label="班级">
              <el-input disabled v-model="data.user.studentInfo.className" />
            </el-form-item>
            <el-form-item label="年级">
              <el-input disabled v-model="data.user.studentInfo.grade" />
            </el-form-item>
            <el-form-item label="政治面貌">
              <el-input
                  disabled
                  :value="getPoliticalStatus(data.user.studentInfo.politicalStatus)"
              />
            </el-form-item>
            <el-form-item label="性别">
              <el-input disabled v-model="data.user.studentInfo.sex" />
            </el-form-item>
            <el-form-item label="所属支部">
              <el-input disabled v-model="data.branchName" />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 头像设置 -->
        <el-tab-pane label="头像设置" name="avatar">
          <div class="avatar-section">
            <div class="avatar-content">
              <h3 class="avatar-title">当前头像</h3>
              <el-upload
                  :show-file-list="false"
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :on-success="handleFileUpload"
                  :before-upload="beforeAvatarUpload"
              >
                <div class="avatar-wrapper">
                  <img v-if="data.user.avatar" :src="data.user.avatar" class="avatar" />
                  <div v-else class="avatar-placeholder">
                    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                  </div>
                  <div class="avatar-hover-mask">
                    <el-icon><Camera /></el-icon>
                    <span>更换头像</span>
                  </div>
                </div>
              </el-upload>
              <div class="avatar-tips">
                <p>支持 JPG、PNG 格式的图片</p>
                <p>图片大小不超过 2MB</p>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="button-section">
        <el-button @click="resetForm" class="reset-button" :disabled="loading">
          取消修改
        </el-button>
        <el-button
            type="primary"
            @click="save"
            class="save-button"
            :loading="loading"
        >
          保存修改
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from "vue"
import { UserFilled, Camera, Plus, Check } from "@element-plus/icons-vue"
import { getUserInfo, setUserInfo } from "@/utils/auth"
import { ElMessage } from "element-plus"
import request from "@/utils/request"

const activeTab = ref("basic")
const loading = ref(false)
const formRef = ref()
const uploadUrl = import.meta.env.VITE_BASE_URL + "/files/upload"

const rules = {
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
  ]
}

const data = reactive({
  user: {},
  originalUser: {}
})

const isStudent = computed(() => {
  return data.user.userType === 5
})

const initUserData = () => {
  const userInfo = getUserInfo()
  if (userInfo.userType === 5) {
    request.get('sysUser/selectById/' + userInfo.studentInfo.userId).then(res => {
      if (userInfo.userType === 5) {
        data.user.studentInfo = {
          ...data.user.studentInfo, // 保留原有的studentInfo属性
          ...res.data.studentInfo, // 覆盖或添加来自响应的studentInfo属性
        };
      }
    })
    try {
      request.get('organizationMember/selectById/' + userInfo.studentInfo.userId).then(res => {
        if (res.code === '200') {
          data.branchName = res.data.branchName
        } else {
          ElMessage.error(res.msg || '团组织查询失败');
        }
      })
    } catch (error) {
      console.error('团组织查询失败:', error);
      ElMessage.error('团组织查询失败');
    }
    data.user = { ...userInfo }
    data.originalUser = { ...userInfo }
  }
  else {
    if (userInfo) {
      if (userInfo.userType === 5 && !userInfo.studentInfo) {
        userInfo.studentInfo = {
          userId: userInfo.id,
          studentNumber: "",
          department: "",
          major: "",
          className: "",
          grade: "",
          politicalStatus: 1,
          sex: ""
        }
      }
      data.user = { ...userInfo }
      data.originalUser = { ...userInfo }
    }
  }
}

const getPoliticalStatus = (status) => {
  const statusMap = {
    2: "共青团员",
    3: "入党积极分子",
    4: "发展对象",
    5: "预备党员",
    6: "正式党员",
  }
  return statusMap[status] || "未知"
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png"
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error("头像只能是 JPG 或 PNG 格式!")
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!")
  }
  return isJPG && isLt2M
}

const handleFileUpload = (response) => {
  if (response.code === "200") {
    data.user.avatar = response.data
    ElMessage.success("头像上传成功")
  } else {
    ElMessage.error("头像上传失败")
  }
}

const save = () => {
  formRef.value.validate((valid) => {
    if (!valid) return

    loading.value = true

    const updateData = {
      id: data.user.id,
      username: data.user.username,
      realName: data.user.realName,
      phone: data.user.phone,
      email: data.user.email,
      avatar: data.user.avatar,
      userType: data.user.userType,
      status: data.user.status
    }

    if (isStudent.value && data.user.studentInfo) {
      updateData.studentInfo = {
        ...data.user.studentInfo,
        userId: data.user.id
      }
    }

    request
        .put("/sysUser/update", updateData)
        .then((res) => {
          loading.value = false
          if (res.code === "200") {
            ElMessage.success("个人信息更新成功")
            const newUserInfo = { ...data.user, ...updateData }
            setUserInfo(newUserInfo)
            Object.assign(data.originalUser, newUserInfo)
            //延迟0.5s刷新页面
            setTimeout(() => {
              window.location.reload()
            }, 500)
          } else {
            ElMessage.error(res.msg || "更新失败")
          }
        })
        .catch((error) => {
          loading.value = false
          ElMessage.error("更新失败：" + (error.message || "请稍后重试"))
        })
  })
}

const resetForm = () => {
  Object.assign(data.user, data.originalUser)
  //formRef.value?.resetFields()
  setTimeout(() => {
    window.location.reload()
  },500)
  ElMessage.info("已取消修改")
}

onMounted(() => {
  initUserData()
})
</script>

<style scoped>
/* 布局优化 */
.profile-container {
  width: 90%;
  max-width: 1200px;
  margin: 24px auto;
}

.profile-card {
  background: linear-gradient(145deg, #f5f5f7, #ffffff);
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

/* 卡片头部 */
.card-header {
  text-align: center;
  margin-bottom: 20px;
}

.profile-title {
  font-size: 24px;
  color: #4a4a4a;
  font-weight: 700;
}

.profile-subtitle {
  color: #7a7a7a;
  font-size: 14px;
  margin-top: 8px;
}

.button-section {
  position: fixed;
  bottom: 24px;
  right: 24px;
  display: flex;
  gap: 16px;
}

.save-button {
  background: linear-gradient(90deg, #c8161d, #e54b4b);
  border-radius: 8px;
  border: none;
  color: white;
  padding: 8px 24px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 8px rgba(200, 22, 29, 0.3);
}

.save-button:hover {
  background: linear-gradient(90deg, #b51418, #d84545);
  transform: translateY(-2px);
}
.avatar-section {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  padding: 20px;
}

.avatar-content {
  text-align: center;
}

.avatar-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 24px;
}

.avatar-wrapper {
  width: 160px;
  height: 160px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  border: 2px dashed #dcdfe6;
  margin: 0 auto;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-wrapper:hover {
  border-color: #c8161d;
}

.avatar-wrapper:hover .avatar-hover-mask {
  opacity: 1;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar-hover-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  color: white;
}

.avatar-hover-mask .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.avatar-hover-mask span {
  font-size: 14px;
}

.avatar-tips {
  margin-top: 16px;
  color: #909399;
  font-size: 13px;
}

.avatar-tips p {
  margin: 4px 0;
}

/* 上传组件自定义样式 */
:deep(.el-upload) {
  width: 100%;
  height: 100%;
  display: block;
}
</style>
